package resolver

import resolver.query.BatchedQuery
import resolver.query.Query
import resolver.query.SynonymQuery
import types.Hit

/**
 * uses the queryClass table for compound lookups
 * User: wohlgemuth
 * Date: Feb 2, 2010
 * Time: 3:27:47 PM
 *
 */
class DatabaseContentResolver extends SplitResolver {

  private static DatabaseContentResolver instance = null;

  //all registered queries which can be run
  private Set<Query> registeredQueries = new HashSet<Query>()


  private DatabaseContentResolver() {
    
    registeredQueries.add(new SynonymQuery())

    this.setBatchEnabledByDefault true
  }

  static DatabaseContentResolver getInstance() {
    if (instance == null) {
      instance = new DatabaseContentResolver()
    }
    return instance
  }

  /**
   *
   * executes a query against the database with the given hit
   */
  Set<Hit> discoverCompound(String value) {

    value = nameCleanup(value)

    Set<Hit> res = new HashSet<Hit>()

    //go over all queries
    registeredQueries.each {Query query ->
      //go over all results
      query.executeQuery(value).each {Hit hit ->

        //add the result to the result set
        res.add(hit)

      }
    }

    //return the result
    return res;
  }



  def HashSet<Hit> workOnBatch(Set<String> batch) {
    Set<Hit> res = new HashSet<Hit>()

    //go over all queries
    registeredQueries.each {Query query ->
      //go over all results
      if (query instanceof BatchedQuery) {
        logger.debug "query is batchable..."
        BatchedQuery bquery = query

        batch.each {String q ->
          bquery.addQuery q
        }

        logger.debug "executing batched query"
        res.addAll(bquery.executeQuery())

      }
      else {
        logger.debug "query is not batchable, so executed in default mode..."

        batch.each {String value ->
          query.executeQuery(value).each {Hit hit ->

            //add the result to the result set
            res.add(hit)

          }
        }
      }
    }
    return super.workOnBatch(batch);    //To change body of overridden methods use File | Settings | File Templates.
  }

}